﻿using LPY.LeHealth.DTO;
using LPY.LeHealth.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LPY.LeHealth.WebSite.Controllers
{
    public class MobileController : BaseController
    {
        private UserService userService;
        private PhysicalService physicalService;
        private CartService carService;
        private OrderService orderService;

        public MobileController()
        {
            userService = new UserService();
            physicalService = new PhysicalService();
            carService = new CartService();
            orderService = new OrderService();
        }

        /// <summary>
        /// 移动端首页
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            var pageSize = 4;
            long totalSize = 0;
            //获取套餐列表
            var comboList = physicalService.GetPhysicalComboDTO(1, pageSize, out totalSize);
            //获取单项体检列表
            var singleList = physicalService.GetPhysicalSingleDTO(1, pageSize, out totalSize);

            ViewBag.ComboList = comboList;
            ViewBag.SingleList = singleList;

            return View();
        }

        /// <summary>
        /// 套餐详情
        /// </summary>
        /// <param name="id">套餐Id</param>
        /// <returns></returns>
        public ActionResult ComboDetail(int id)
        {
            var combo = physicalService.GetCombo(id);
            ViewBag.Combo = combo;

            return View();
        }
        /// <summary>
        /// 套餐详情
        /// </summary>
        /// <param name="id">套餐Id</param>
        /// <returns></returns>
      [HttpPost]
        public ActionResult tj_list_details_show(int id)
        {
            var combo = physicalService.GetCombo(id);


            return Json(combo);
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        public ActionResult Login()
        {
            return View();
        }

        /// <summary>
        /// 用户名密码登录
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult NameLogin(string name, string pwd, string ReturnUrl)
        {
            var data = new Common.JsonMessage();

            var usr = userService.Login(name, pwd);
            if(null!=usr)
            {
                Session[CommonService.UserSessionName] = usr;
                data.Code = 1;
                data.Msg = "登录成功";
                data.Data = "http://" + Request.Url.Authority + "/" + ReturnUrl;
            }
            else
            {
                data.Code = 0;
                data.Msg = "登录失败";
            }

            return Json(data);
        }

        /// <summary>
        /// 手机号码登录
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult PhoneLogin(string phone, string code, string ReturnUrl)
        {
            var data = new Common.JsonMessage();
            var sc = Session[phone].ToString();
            if (code == sc)
            {
                var usr = userService.Login(phone);
                if (null != usr)
                {
                    Session[CommonService.UserSessionName] = usr;
                    data.Code = 1;
                    data.Msg = "登录成功";
                    if(!string.IsNullOrEmpty(ReturnUrl))
                    {
                        data.Data ="http://"+ Request.Url.Authority+"/" + ReturnUrl;
                    }
                    
                }
                else
                {
                    data.Code = 0;
                    data.Msg = "登录失败";
                }
            }
            else
            {
                data.Code = 0;
                data.Msg = "验证码无效";
            }

            return Json(data);
        }

        /// <summary>
        /// 注册
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Register(string name,string pwd,string phone,string code)
        {
            var result = false;
            var data = new Common.JsonMessage();

            //非空判断
            if(!(string.IsNullOrEmpty(name) 
                || string.IsNullOrEmpty(pwd)
                || string.IsNullOrEmpty(phone)
                || string.IsNullOrEmpty(code)))
            {
                var sc = Session[phone].ToString();
                if(code==sc)
                {
                    result = userService.Register(name, pwd, phone);
                    Session[phone] = "";
                    if (result)
                    {
                        data.Code = 1;
                        data.Msg = "注册成功";
                    }
                    else
                    {
                        data.Code = 0;
                        data.Msg = "注册失败";
                    }
                }
                else
                {
                    data.Code = 0;
                    data.Msg = "短信验证码无效";
                }
            }
            else
            {
                data.Code = 0;
                data.Msg = "注册信息不全";
            }
            
            return Json(data);
        }

        /// <summary>
        /// 获取（发送）验证码
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetSecurityCode(string phone)
        {
            //验证码有有效期设置（10分钟）成功之后失效
            var code= Common.SecurityHelper.CreateCode(5);
            Session[phone] = code;
            Session.Timeout = 10;

            var data = new Common.JsonMessage();
            data.Code = 1;
            data.Msg = "处理成功";
            data.Data = code;

            //todo:发送到用户手机

            return Json(data);

        }

        /// <summary>
        /// 用户中心
        /// </summary>
        /// <returns></returns>
        [Common.MobileUser]
        public ActionResult UserCenter()
        {
            var osc= orderService.GetOrderStateCount(CurrentUser.Id);
            ViewBag.PayCount = osc[0];//支付数量
            ViewBag.AppointCount = osc[1];//预约数量
            ViewBag.PhysicalCount = osc[2];//体检数量
            return View();
        }

        /// <summary>
        /// 购物车
        /// </summary>
        /// <returns></returns>
        [Common.MobileUser]
        public ActionResult Cart()
        {
            //购物车列表
            var comboList = carService.GetListByUserId(CurrentUser.Id);
            ViewBag.ComboList = comboList;

            return View();
        }

        //移除购物车的项
        [Common.MobileUser]
        public ActionResult CartRemove(int id)
        {
            var result= carService.DeleteItem(id);
            var js = new Common.JsonMessage();
            if(result)
            {
                js.Code = 1;
                js.Msg = "移除成功";
            }
            else
            {
                js.Code = 0;
                js.Msg = "移除失败";
            }
            return Json(js);
        }

        //更新购物数量
        [Common.MobileUser]
        public ActionResult CartCount(int id,bool isAdd)
        {
            int addCount = isAdd ? 1 : -1;
            int count;
            var result= carService.UpdateCount(id, addCount, out count);
            var data = new Common.JsonMessage();
            if(result)
            {
                data.Code = 1;
                data.Msg = "操作成功";
                data.Data = count;
            }
            else
            {
                data.Code = 0;
                data.Msg = "操作失败";
            }
            return Json(data);
        }

        /// <summary>
        /// 订单
        /// </summary>
        /// <returns></returns>
        [Common.MobileUser]
        public ActionResult Order()
        {
            //购物车列表
            var comboList = carService.GetListByUserId(CurrentUser.Id);
            ViewBag.ComboList = comboList;

            return View();
        }

        /// <summary>
        /// 添加订单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Common.MobileUser]
        public ActionResult AddOrder(string name, string phone, string code,/* 0-男 1-女 */ int gender,/*优惠券Id*/ int couponid, int paytype = 0)
        {
            var data = new Common.JsonMessage();

            //订单人信息验证
            if (string.IsNullOrEmpty(code))
            {
                data.Code = 0;
                data.Msg = "短信验证码不能为空";
            }
            else if(string.IsNullOrEmpty(name))
            {
                data.Code = 0;
                data.Msg = "订单人姓名必填";
            }
            else
            {
                //短信码验证
                var sc = Session[phone].ToString();
                if (code == sc)
                {
                    //优惠处理

                    //创建订单
                    var order = new Order();
                    //order.Ordercode = Guid.NewGuid().ToString();// "";//订单编号
                    order.PayCode = "";//支付完成后才有交易号
                    order.UserId = CurrentUser.Id;//用户Id
                    //order.SumPrice = total;//订单总价
                    order.PreferentialPrice = 0;//优惠价格
                    //order.CreateDate = DateTime.Now;
                    order.BookerName = name;
                    order.BookerPhone = phone;
                    order.BookerSex = gender;
                    order.State = 0;//未支付状态
                    order.PayType = paytype;
                    order.ValidateCode = Common.SecurityHelper.CreateCode(6);//6位随机验证码

                    var id= orderService.CreateOrder(order);

                    //订单创建成功移除购物车数据
                    if(id>0)
                    {
                        data.Code = 1;
                        data.Msg = "添加订单成功";
                        data.Data = "http://" + Request.Url.Authority + "/Mobile/OrderResult/" + id;
                    }
                    else
                    {
                        data.Code = 1;
                        data.Msg = "添加订单失败";
                    }

                    //RedirectToAction("OrderResult",)
                }
                else
                {
                    data.Code = 0;
                    data.Msg = "短信验证码无效";
                }
            }

            return Json(data);
            //return View();
        }

        [Common.MobileUser]
        public ActionResult OrderResult(int id)
        {
            var data = orderService.GetById(id);
            ViewBag.OrderId = id;
            ViewBag.Data = data;
            return View();
        }

        /// <summary>
        /// 支付
        /// </summary>
        /// <returns></returns>
        [Common.MobileUser]
        public ActionResult Pay(int id)
        {
            //根据订单Id，进行支付逻辑
            var data = orderService.GetById(id);
            /*
            //商户订单号
            string out_trade_no = data.Ordercode;

            //订单名称，必填
            
            string subject = data.

            //付款金额，必填
            string total_fee = data.SumPrice.ToString();

            //收银台页面上，商品展示的超链接，必填
            string show_url = WIDshow_url.Text.Trim();

            //商品描述，可空
            string body = WIDbody.Text.Trim();



            ////////////////////////////////////////////////////////////////////////////////////////////////

            //把请求参数打包成数组
            SortedDictionary<string, string> sParaTemp = new SortedDictionary<string, string>();
            sParaTemp.Add("partner", Config.partner);
            sParaTemp.Add("seller_id", Config.seller_id);
            sParaTemp.Add("_input_charset", Config.input_charset.ToLower());
            sParaTemp.Add("service", Config.service);
            sParaTemp.Add("payment_type", Config.payment_type);
            sParaTemp.Add("notify_url", Config.notify_url);
            sParaTemp.Add("return_url", Config.return_url);
            sParaTemp.Add("out_trade_no", out_trade_no);
            sParaTemp.Add("subject", subject);
            sParaTemp.Add("total_fee", total_fee);
            sParaTemp.Add("show_url", show_url);
            //sParaTemp.Add("app_pay","Y");//启用此参数可唤起钱包APP支付。
            sParaTemp.Add("body", body);
            //其他业务参数根据在线开发文档，添加参数.文档地址:https://doc.open.alipay.com/doc2/detail.htm?spm=a219a.7629140.0.0.2Z6TSk&treeId=60&articleId=103693&docType=1
            //如sParaTemp.Add("参数名","参数值");

            //建立请求
            string sHtmlText = Submit.BuildRequest(sParaTemp, "get", "确认");
            Response.Write(sHtmlText);


            //支付成功更新订单状态
            orderService.UpdateOrderState(id, OrderState.ToAppointment);

            
            */

            ViewBag.OrderId = id;
            return View();
        }

        /// <summary>
        /// 预约
        /// </summary>
        /// <returns></returns>
        [Common.MobileUser]
        public ActionResult Appointment(int id)
        {
            ViewBag.OrderId = id;
            return View();
        }

        [HttpPost]
        [Common.MobileUser]
        public ActionResult Appointment(AppointmentViewModel vm)
        {
            var data = new Common.JsonMessage();

            List<PhysicalPeople> info = new List<PhysicalPeople>();
            PhysicalPeople peo;
            for (int i = 0; i < vm.info.Count; i++)
            {
                peo = new PhysicalPeople();
                peo.OrderId = vm.orderid;
                peo.Name = vm.info[i].name;
                peo.Phone = vm.info[i].phone;
                peo.AppointmentTime = vm.info[i].time;
                peo.Gender = vm.info[i].gender;
                info.Add(peo);
            }

            var result = orderService.AddAppointmentInfo(info);
            if(result)
            {
                //更新订单状态
                orderService.UpdateOrderState(vm.orderid, OrderState.ToPhysical);

                data.Code = 1;
                data.Msg = "添加成功";
            }
            else
            {
                data.Code = 0;
                data.Msg = "添加失败";
            }
            return Json(data);
        }

        //预约结果
        public ActionResult AppointmentResult()
        {
            return View();
        }

        /// <summary>
        /// 体检套餐列表
        /// </summary>
        /// <returns></returns>
        public ActionResult Combo()
        {
            var pageSize = 10;
            long totalSize = 0;
            //获取套餐列表
            var comboList = physicalService.GetPhysicalComboDTO(1, pageSize, out totalSize);
            
            ViewBag.ComboList = comboList;
            return View();
        }

        /// <summary>
        /// 单项体检列表
        /// </summary>
        /// <returns></returns>
        public ActionResult Single()
        {
            var pageSize = 10;
            long totalSize = 0;
            //获取单项体检列表
            var singleList = physicalService.GetPhysicalSingleDTO(1, pageSize, out totalSize);

            ViewBag.SingleList = singleList;
            return View();
        }

        /// <summary>
        /// 我的订单
        /// </summary>
        /// <returns></returns>
        [Common.MobileUser]
        public ActionResult OrderManager(int state=-1)
        {
            var osc = orderService.GetOrderStateCount(CurrentUser.Id);
            ViewBag.PayCount = osc[0];//支付数量
            ViewBag.AppointCount = osc[1];//预约数量
            ViewBag.PhysicalCount = osc[2];//体检数量

            List<Order> orders=new List<Order>();
            orders=orderService.GetOrderList(CurrentUser.Id,state);

            ViewBag.OrderList = orders;
            return View();
        }

        /// <summary>
        /// 订单详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Common.MobileUser]
        public ActionResult OrderDetails(int id)
        {
            var orderDetails = orderService.GetOrderDetails(id);
            ViewBag.OrderDetails = orderDetails;

            var pps= orderService.GetPhysicalPeopleByOrderId(id);
            ViewBag.PhysicalPeoples = pps;

            return View();
        }
	}

    #region ViewModel（预约信息）

    public class AppointmentInfo
    {
        public string name { get; set; }
        public string phone { get; set; }
        public DateTime time { get; set; }
        public int gender { get; set; }
    }
    public class AppointmentViewModel
    {
        public int orderid { get; set; }
        public List<AppointmentInfo> info { get;set; }
    }

    #endregion
}